<template>
  <el-dialog
    v-model="dialogImportExcel.visible"
    :title="dialogImportExcel.title"
    draggable
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    close-icon="CloseBold"
    @close="closeDialog(false)"
  >
    <div class="app-container">
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" :rules="rules" label-width="120">
          <el-row :gutter="20" :justify="'start'">
            <el-col :span="7" :offset="0">
              <el-form-item label="选择文件" prop="fileName">
                <el-upload
                  ref="uploadRef"
                  v-model:file-list="fileList"
                  :show-file-list="false"
                  style="padding-top: 4px"
                  :action="actionUrl"
                  :headers="headers"
                  :auto-upload="false"
                  :on-error="handleError"
                  :on-success="handleSuccess"
                  :on-change="handleChange"
                  :limit="1"
                  :accept="'.xlsx, .xls'"
                  :on-exceed="handleExceed"
                >
                  <template #trigger>
                    <el-input v-model="queryParams.fileName" placeholder="请选择文件" clearable readonly />
                  </template>
                  <el-button
                    type="primary"
                    plain
                    :loading="loading"
                    style="position: absolute; right: -100px"
                    @click.stop="ImportFile"
                  >
                    导入 Excel
                  </el-button>

                  <template #tip>
                    <div class="el-upload__tip text-red">限制上传单文件，格式.xlsx, .xls</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="17" style="padding-right: 10px; height: 45px; padding-left: 100px">
              <download-template :type="101"></download-template
            ></el-col>
          </el-row>
        </el-form>
      </div>

      <el-card shadow="never">
        <el-row :gutter="20" justify="start">
          <el-col :offset="0" class="table-tips">
            <el-text> 导入标识:</el-text>
            <el-text type="primary"> <CirclePlus /> 新增数据 </el-text>
            <el-text type="success"> <CircleCheck /> 验证通过 </el-text>
            <el-text type="warning"> <Warning />验证不通过,但是不影响导入 </el-text>
            <el-text type="danger"> <CircleClose />验证失败 </el-text>
          </el-col>
          <el-col :offset="0" class="table-tips">
            <el-text> 对口部门:</el-text>
            <el-text type="danger">{{ projectIndustryTypes.map((i: any) => i.label).join(",") }} </el-text>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="tableList" border :style="{ height: tableHeight, marginTop: `10px` }">
          <el-table-column label="序号" type="index" min-width="60" align="center"></el-table-column>
          <el-table-column label="项目来源" min-width="120" align="center" prop="dataSource">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.DataSource" placement="top">
                <el-text :type="scope.row.fieldImportLevel.DataSource">
                  <CircleCheck v-if="scope.row.fieldImportLevel.DataSource == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.DataSource == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.DataSource == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.DataSource == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.dataSource }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="项目编号(招标标段编号)" min-width="170" align="center" prop="biddingSectionNum">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.BiddingSectionNum" placement="top">
                <el-text :type="scope.row.fieldImportLevel.BiddingSectionNum">
                  <CircleCheck v-if="scope.row.fieldImportLevel.BiddingSectionNum == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.BiddingSectionNum == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.BiddingSectionNum == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.BiddingSectionNum == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.biddingSectionNum }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="项目名称" min-width="160" align="center" prop="name">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.Name" placement="top">
                <el-text :type="scope.row.fieldImportLevel.Name">
                  <CircleCheck v-if="scope.row.fieldImportLevel.Name == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.Name == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.Name == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.Name == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.name }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="中标单位" min-width="170" align="center" prop="lumpContractorCorpName">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.LumpContractorCorpName" placement="top">
                <el-text :type="scope.row.fieldImportLevel.LumpContractorCorpName">
                  <CircleCheck v-if="scope.row.fieldImportLevel.LumpContractorCorpName == 'success'" />
                  <Warning
                    v-if="scope.row.fieldImportLevel.LumpContractorCorpName == 'warning' && scope.row.name != ''"
                  />
                  <CircleClose v-if="scope.row.fieldImportLevel.LumpContractorCorpName == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.LumpContractorCorpName == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.lumpContractorCorpName }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="中标单位信用代码" min-width="160" align="center" prop="lumpContractorCorpCode">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.LumpContractorCorpCode" placement="top">
                <el-text :type="scope.row.fieldImportLevel.LumpContractorCorpCode">
                  <CircleCheck v-if="scope.row.fieldImportLevel.LumpContractorCorpCode == 'success'" />
                  <Warning
                    v-if="scope.row.fieldImportLevel.LumpContractorCorpCode == 'warning' && scope.row.name != ''"
                  />
                  <CircleClose v-if="scope.row.fieldImportLevel.LumpContractorCorpCode == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.LumpContractorCorpCode == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.lumpContractorCorpCode }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="建设单位" min-width="180" align="center" prop="buildCorpName">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.BuildCorpName" placement="top">
                <el-text :type="scope.row.fieldImportLevel.BuildCorpName">
                  <CircleCheck v-if="scope.row.fieldImportLevel.BuildCorpName == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.BuildCorpName == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.BuildCorpName == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.BuildCorpName == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.buildCorpName }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="中标金额" min-width="120" prop="contractAmount">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.ContractAmount" placement="top">
                <el-text :type="scope.row.fieldImportLevel.ContractAmount">
                  <CircleCheck v-if="scope.row.fieldImportLevel.ContractAmount == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.ContractAmount == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.ContractAmount == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.ContractAmount == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.contractAmount }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="计划开工日期" min-width="160" align="center" prop="contractStartDate">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.ContractStartDate" placement="top">
                <el-text :type="scope.row.fieldImportLevel.ContractStartDate">
                  <CircleCheck v-if="scope.row.fieldImportLevel.ContractStartDate == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.ContractStartDate == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.ContractStartDate == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.ContractStartDate == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.contractStartDate }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="计划完工日期" min-width="160" align="center" prop="contractEndDate">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.ContractEndDate" placement="top">
                <el-text :type="scope.row.fieldImportLevel.ContractEndDate">
                  <CircleCheck v-if="scope.row.fieldImportLevel.ContractEndDate == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.ContractEndDate == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.ContractEndDate == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.ContractEndDate == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.contractEndDate }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="对口部门" min-width="100" align="center" prop="industryType">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.IndustryType" placement="top">
                <el-text :type="scope.row.fieldImportLevel.IndustryType">
                  <CircleCheck v-if="scope.row.fieldImportLevel.IndustryType == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.IndustryType == 'warning' && scope.row.name != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.IndustryType == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.IndustryType == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.industryType }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="所属市" min-width="100" align="center" prop="cityName">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.CityName" placement="top">
                <el-text :type="scope.row.fieldImportLevel.CityName">
                  <CircleCheck v-if="scope.row.fieldImportLevel.CityName == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.CityName == 'warning' && scope.row.cityName != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.CityName == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.CityName == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.cityName }}</el-text>
            </template></el-table-column
          >
          <el-table-column label="所属县" min-width="100" align="center" prop="areaName">
            <template #default="scope">
              <el-tooltip effect="light" :content="scope.row.fieldImportMsg.AreaName" placement="top">
                <el-text :type="scope.row.fieldImportLevel.AreaName">
                  <CircleCheck v-if="scope.row.fieldImportLevel.AreaName == 'success'" />
                  <Warning v-if="scope.row.fieldImportLevel.AreaName == 'warning' && scope.row.areaName != ''" />
                  <CircleClose v-if="scope.row.fieldImportLevel.AreaName == 'danger'" />
                  <CirclePlus v-if="scope.row.fieldImportLevel.AreaName == 'primary'" />
                </el-text>
              </el-tooltip>
              <el-text>{{ scope.row.areaName }}</el-text>
            </template></el-table-column
          >
        </el-table>
      </el-card>
    </div>
    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="submitloading" @click="handleSubmit">保存 </el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useUserStore } from "@/store/modules/user";
import type { UploadUserFile, UploadFiles, UploadFile } from "element-plus";
import { useScreen } from "@/store/modules/screen";
import { ImportProject } from "@/api/project/projectInfo/index";
import DownloadTemplate from "@/views/common/DownloadTemplate/index.vue";
import { getDicts } from "@/store/modules/dict";

//项目行业主管部门
const projectIndustryTypes = getDicts("industryTypes");
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(1500);
const tableHeight = computed(() => {
  if (screenStore.screenHeight - 117 - 180 - 60 < 360) {
    return 360;
  } else {
    return screenStore.screenHeight - 117 - 180 - 60;
  }
});
const itemSpan = ref(12);

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = screenStore.screenWidth - 100;
    itemSpan.value = 12;
  }
}

const useUser = useUserStore();
let props = defineProps({
  dialogImportExcel: {
    type: Object,
    default: () => ({
      visible: false,
      title: "导入",
      id: 0,
      footBtn: "提交",
    }),
  },
});
const { dialogImportExcel } = toRefs(props);
const queryParams = reactive({
  fileName: "",
});
const fileList = ref<UploadUserFile[]>([]);
const uploadRef = ref();
const queryFormRef = ref();
const loading = ref(false);
const submitloading = ref(false);

const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/sysuser/project/import`);
const tableList = ref<any[]>();
let headers = ref({
  Authorization: useUser.token,
});
const rules = {
  fileName: [
    {
      required: true,
      trigger: "change",
      validator: fileNameBlur,
    },
  ],
};

function fileNameBlur(rule: any, value: any, callback: any) {
  if (!value || value === undefined || value === "") {
    callback(new Error(""));
    return;
  } else {
    let temp = value.split(".");
    if (temp[temp.length - 1] == "xlsx" || temp[temp.length - 1] == "xls") {
      callback();
    } else {
      callback(new Error("请上传指定文件格式！"));
    }
  }
}

const emit = defineEmits(["sendClose"]);

onMounted(async () => {
  initScreen();
});

function handleSubmit() {
  submitloading.value = true;
  if (tableList.value === undefined || tableList.value.length === 0) {
    ElMessage.warning("请先导入数据");
    submitloading.value = false;
    return;
  }
  let allowed = true;
  tableList.value.forEach((item) => {
    if (item.errorCount > 0) {
      allowed = false;
    }
  });
  if (!allowed) {
    ElMessage.warning("存在错误数据，请检查");
    submitloading.value = true;
    return;
  }

  ImportProject(tableList.value)
    .then((resp) => {
      if (resp.success === true) {
        ElMessage.success("导入成功");
        closeDialog(true);
      } else {
        ElMessage.warning(resp.msg);
        submitloading.value = false;
      }
    })
    .finally(() => {
      submitloading.value = false;
    });
}

/**
 * 重置表单
 */
function resetForm() {
  queryFormRef.value?.resetFields();
  tableList.value = [];
}

/* 上传超限 */
const handleExceed = (files: File[], uploadFiles: UploadUserFile[]) => {
  const file = files[0];
  uploadRef.value?.handleStart(file);
};

const handleRemove = () => {
  fileList.value.forEach((item) => {
    item.status = "ready";
  });
};

/* 上传成功 */
function handleSuccess(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) {
  if (!response.success) {
    handleRemove();
    ElMessage.error(response.msg);
    loading.value = false;
    return;
  }
  handleRemove();
  tableList.value = response.data;
  loading.value = false;
}

/* 文件改变 */
function handleChange(uploadFile: UploadFile, uploadFiles: UploadFiles) {
  fileList.value = [];
  fileList.value.push(uploadFile);
  queryParams.fileName = uploadFile.name;
}

/*上传失败*/
function handleError(error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) {
  ElMessage.error(error);
  handleRemove();
  loading.value = false;
}

function sendIntoClose(refresh: boolean) {
  emit("sendClose", refresh);
}

/* 导入 */
function ImportFile() {
  queryFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      uploadRef.value!.submit();
    }
  });
}

/* 删除 */
function handleDelete(index: number) {
  tableList.value?.splice(index, 1); //对tableData中的数据删除一行
}

function closeDialog(refresh: boolean) {
  sendIntoClose(refresh);
  resetForm();
}
</script>

<style lang="less" scoped>
.app-container {
  padding: 0px;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

:deep(.el-form-item) {
  width: 100%;
}

:deep(.el-form-item__content div) {
  width: 100%;
}

:deep(.el-upload__tip) {
  width: 100%;
}

:deep(.cell) {
  display: flex;
  justify-content: center;
}

:deep(.el-text) {
  justify-content: center;
  display: flex;
  cursor: pointer;
}

:deep(.el-text svg) {
  width: 20px;
  margin-right: 5px;
}

:deep(.table-tips) {
  display: inline-flex !important;
  padding-top: 10px;
}

:deep(.table-tips .el-text) {
  padding: 0 15px;
}

.text-red {
  color: var(--el-color-danger);
}
</style>
